package com.linkage.jz.bankruptcy.activity.RegistLogin;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingPhoneActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public class GetPwdOneActivity extends BaseWhiteActivity implements OnClickListener {
    private static final String TAG = GetPwdOneActivity.class.getSimpleName();
    private ShapeLoadingDialog shapeLoadingDialog;

    public static void start(Context context) {
        Intent intent = new Intent(context, GetPwdOneActivity.class);
        context.startActivity(intent);
    }

    EditText et_phone;
    EditText et_vcode;
    TextView getcode, btn_next;
    MyCountDownTimer myCountDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_getpwd_one, "找回密码");
        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        myCountDownTimer = new MyCountDownTimer(60000, 1000);

        et_phone = findViewById(R.id.et_phone);
        getcode = findViewById(R.id.getcode);
        btn_next = findViewById(R.id.btn_next);
        et_vcode = findViewById(R.id.et_vcode);

        btn_next.setOnClickListener(this);
        getcode.setOnClickListener(this);

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());


                showSave();
                showCode();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        et_vcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());


                showSave();
                showCode();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        showCode();

        showSave();
    }

    private void showCode()
    {
        String str1 =  et_phone.getText().toString().trim();
        if(str1.equalsIgnoreCase(""))
        {
            getcode.setClickable(false);
            getcode.setTextColor(getResources().getColor(R.color.btnosel));
        }else{
            getcode.setClickable(true);
            getcode.setTextColor(getResources().getColor(R.color.btsel));
        }
    }

    private void showSave()
    {
        String str1 =  et_phone.getText().toString().trim();
        String str2 =  et_vcode.getText().toString().trim();


        if(!str1.equalsIgnoreCase("") && !str2.equalsIgnoreCase("") )
        {

            btn_next.setClickable(true);
            btn_next.setBackgroundResource((R.drawable.login_corner_btn));
        }else{
            btn_next.setClickable(false);
            btn_next.setBackgroundResource((R.drawable.login_corner_nosel_btn));
        }


    }


    @Override
    public void onClick(View view) {

        String phone = "";
        switch (view.getId()) {

            case R.id.getcode:
                phone = et_phone.getText().toString();
                if ("".equalsIgnoreCase(phone)) {
                    showToast("手机号不能为空");
                    return;
                }

                getSMSCode(phone);
                break;

            case R.id.btn_next:
                phone = et_phone.getText().toString();
                if ("".equalsIgnoreCase(phone)) {
                    showToast("手机号不能为空");
                    return;
                }

                String code = et_vcode.getText().toString();
                if ("".equalsIgnoreCase(code)) {
                    showToast("验证码不能为空");
                    return;
                }
                checkSMSCode(phone,code);
                break;
            default:
                break;
        }

    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getcode.setClickable(false);
            getcode.setText(l / 1000 + "秒");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getcode.setText("重新获取");
            //设置可点击
            getcode.setClickable(true);
        }
    }



    public void checkSMSCode(final String mobile,final String captcha) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
//        params.put("appid",Consts.APPID);
//        params.put("nonce", rom);
//        params.put("timestamp", timestamp);
//
//        String sign = SignUtil.createSign(Consts.APPKEY,params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("mobile", mobile)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("captcha", captcha)
                .build();

        String url = Consts.WEBURL_CHECKCAP;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                GetPwdTwoActivity.start(GetPwdOneActivity.this, mobile,  captcha);
                                finish();
                                //更新UI
//                                Toast.makeText(GetPwdOneActivity.this, "请求成功，请查看短信" + object.optString("data"), Toast.LENGTH_SHORT).show();
                            }

                        });

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("请求失败"+object.optString("msg"));
                            }

                        });
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }


    public void getSMSCode(String mobile) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
//        params.put("appid",Consts.APPID);
//        params.put("nonce", rom);
//        params.put("timestamp", timestamp);
//
//        String sign = SignUtil.createSign(Consts.APPKEY,params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("mobile", mobile)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("reg", "false")
                .add("source", "5")
                .build();

        String url = Consts.WEBURL_SMSCAPTCHA;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                myCountDownTimer.start();
                                showToast("请求成功" + object.optString("data"));
//                                Toast.makeText(GetPwdOneActivity.this, "请求成功，请查看短信" + object.optString("data"), Toast.LENGTH_SHORT).show();
                            }

                        });

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("请求失败"+object.optString("msg"));
                            }

                        });
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}

